const db = require('../db/Model/model')
const uuid = require('node-uuid')
const Token = require('./token')
const JwtKey = '__My project Blog __  I can do it now ___??((::KKPP__((__'
const dayjs = require('dayjs')


// 注册
function register(req, res) {
    const { username, password } = req.body
    db.userModel.findOne({ username }, (err, doc) => {
        if (err) {
            return res.send({
                msg: err.message,
                state: 500
            })
        } else {
            const _id = uuid()
            if (doc === null) {
                db.userModel.create({ _id, username, password }, (err, result) => {
                    if (err) {
                        return res.send({
                            msg: err.message,
                            state: 500
                        })

                    } else {
                        return res.send({
                            msg: "注册成功",
                            state: 200
                        })
                    }
                })
            } else {
                return res.send({
                    msg: "该用户已存在",
                    state: 200
                })
            }
        }
    })
}

// 登陆
function login(req, res) {
    const { username, password } = req.body
    db.userModel.findOne({ username, password }, (err, doc) => {
        if (err) {
            return res.send({
                msg: err.message,
                state: 500,
            })
        } else {
            if (doc !== null && username === doc.username && password === doc.password) {
                const token = Token.encryptionToken(doc._id, JwtKey)
                db.userModel.updateOne(
                    { _id: doc._id },
                    {
                        "$set": {
                            token,
                        }
                    },
                    (err, result) => {
                        if (err) {
                            return res.send({
                                msg: err.message,
                                state: 500
                            })
                        } else {
                            return res.send({
                                msg: "登陆成功",
                                data: {
                                    token,
                                    username: doc.username
                                }
                            })
                        }
                    }
                )
            } else {
                return res.send({
                    msg: "该用户不存在，请注册后登陆",
                    state: 200
                })
            }
        }
    })
}

// 获取首页数据
function getHomePageDate(req, res) {
    const type = req.query.type
    db.postsModel.find({ type }, (err, docs) => {
        if (err) {
            return res.send({
                msg: err.message,
                state: 500
            })
        } else {
            if (docs !== null) {
                let list = timeSort(docs, 'addTime')
                return res.send({
                    msg: "获取成功",
                    data: {
                        list
                    }
                })
            } else {

                return res.send({
                    msg: "无此类型数据"
                })
            }

        }
    })
}

// 查询作者信息
function getArouthInfo(req, res) {
    const token = checkToken(req)

    const _id = req.query._id
    console.log(_id)
    db.userModel.findOne({ _id }, (err, doc) => {
        if (err) {
            return res.send({
                msg: err.message,
                state: 500
            })
        } else {
            if (doc !== null) {
                return res.send({
                    msg: "查询成功",
                    state: 200,
                    data: {
                        username: doc.username
                    }
                })
            } else {
                return res.send({
                    msg: "无此用户",
                    state: 203
                })
            }
        }
    })


}

// 时间排序
function timeSort(list, p) {
    for (let i = 0; i < list.length - 1; i++) {
        for (let j = 0; j < list.length - 1 - i; j++) {
            if (Date.parse(list[j][p]) < Date.parse(list[j + 1][p])) {
                let temp = list[j]
                list[j] = list[j + 1]
                list[j + 1] = temp
            }
        }
    }

    return list
}

// 校验
function checkToken(req) {
    const tokenObj = Token.decryptToken(req.headers.token, JwtKey)
    return tokenObj
}

// 获取一个帖子信息
function getPostsInfo(req, res) {
    const token = checkToken(req, res)

    const _id = req.query._id
    db.postsModel.findOne({ _id }, (err, doc) => {
        if (err) {
            return res.send({
                msg: err.message,
                state: 500
            })
        } else {
            if (doc !== null) {
                return res.send({
                    msg: "查找成功",
                    state: 200,
                    data: {
                        doc
                    }
                })
            } else {
                return res.send({
                    msg: "无此数据",
                    state: 203
                })
            }
        }
    })

}

// 添加收藏和点赞
function addCollection(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({
            msg: "无效token",
            state: 204
        })
    } else {
        const user_id = token._id
        let { item, type } = req.body
        // 如果类型为收藏  将数据添加到收藏数组中
        if (type === '收藏') {
            db.userModel.updateOne({ _id: user_id }, {
                "$addToSet": {
                    'myCollection': item
                }
            }, (err, result) => {
                if (err) {
                    return res.send({
                        msg: err.message,
                        state: 500
                    })
                } else {
                    return res.send({
                        msg: "数据添加成功",
                        state: 200
                    })
                }
            })
        }
        // 如果类型为点赞，将数据添加到点赞数组中
        else if (type = "点赞") {
            db.userModel.updateOne({ _id: user_id }, {
                "$addToSet": {
                    'myCommen': item
                }
            }, (err, result) => {
                if (err) {
                    return res.send({
                        msg: err.message,
                        state: 500
                    })
                } else {
                    return res.send({
                        msg: "数据添加成功",
                        state: 200
                    })
                }
            })
        }
    }
}

// 取消点赞和收藏
function removeCollectionOrComment(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({
            msg: "无效token",
            state: 204
        })
    }
    else {
        const user_id = token._id
        const { type, item } = req.body
        console.log(item)
        if (type === '点赞') {
            db.userModel.updateOne(
                { _id: user_id },
                {
                    "$pull": {
                        'myCommen': {
                            _id: item._id
                        }
                    }
                }, (err, result) => {
                    if (err) {
                        return res.send({
                            state: 500,
                            msg: err.message
                        })
                    } else {
                        return res.send({
                            state: 200,
                            msg: "数据移除成功"
                        })
                    }
                }
            )
        }
        else if (type === '收藏') {
            db.userModel.updateOne(
                { _id: user_id },
                {
                    "$pull": {
                        'myCollection': {
                            _id: item._id
                        }
                    }
                }, (err, result) => {
                    if (err) {
                        return res.send({
                            state: 500,
                            msg: err.message
                        })
                    } else {
                        return res.send({
                            state: 200,
                            msg: "数据移除成功"
                        })
                    }
                }
            )
        }
    }
}

// 获取用户收藏或点赞的数据
function getUserCollectOrCommitData(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({
            msg: "无效token",
            state: 204
        })
    } else {
        const user_id = token._id
        const type = req.query.type
        if (type === '收藏') {
            db.userModel.findOne({ _id: user_id }, (err, doc) => {
                if (err) {
                    return res.send({
                        msg: err.message,
                        state: 500
                    })
                } else {
                    return res.send({
                        msg: "获取成功",
                        data: {
                            myCollection: doc.myCollection
                        }
                    })
                }
            })
        } else if (type === '点赞') {
            db.userModel.findOne({ _id: user_id }, (err, doc) => {
                if (err) {
                    return res.send({
                        msg: err.message,
                        state: 500
                    })
                } else {
                    return res.send({
                        msg: "获取成功",
                        data: {
                            myCollection: doc.myCommen
                        }
                    })
                }
            })
        }
    }
}

// 增加浏览量
function addLook(req, res) {
    const _id = req.body._id;
    db.postsModel.findOne({ _id }, (err, doc) => {
        if (err) {
            return res.send({
                msg: err.message,
                state: 500
            })
        } else {
            const look = doc.look
            db.postsModel.updateOne({ _id }, {
                "$set": {
                    "look": look + 1
                }
            }, (err, doc) => {
                return res.send({
                    msg: "增加成功",
                    state: 200
                })
            })
        }
    })

}

// 增加点赞数量和收藏数量
function addCollectOrCommentNum(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({
            msg: "无效token",
            state: 204
        })
    } else {
        const user_id = token._id
        const { type, item } = req.body
        if (type === '收藏') {
            db.postsModel.findOne({ _id: item._id }, (err, doc) => {
                if (err) {
                    return res.send({
                        msg: err.message,
                        state: 500
                    })
                } else {
                    db.postsModel.updateOne(
                        { _id: item._id },
                        {
                            "$set": {
                                "collect": doc.collect + 1
                            }
                        },
                        (err, result) => {
                            if (err) {
                                return res.send({
                                    msg: err.message,
                                    state: 500
                                })
                            } else {
                                return res.send({
                                    msg: '更新成功',
                                    state: 200
                                })
                            }
                        })
                }
            })
        } else if (type === '点赞') {
            db.postsModel.findOne({ _id: item._id }, (err, doc) => {
                if (err) {
                    return res.send({
                        msg: err.message,
                        state: 500
                    })
                } else {
                    db.postsModel.updateOne(
                        { _id: item._id },
                        {
                            "$set": {
                                "giveup": doc.giveup + 1
                            }
                        },
                        (err, result) => {
                            if (err) {
                                return res.send({
                                    msg: err.message,
                                    state: 500
                                })
                            } else {
                                return res.send({
                                    msg: '更新成功',
                                    state: 200
                                })
                            }
                        })
                }
            })
        }
    }
}

// 减少点赞数量和收藏数
function removeCollectOrCommentNum(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({
            msg: "无效token",
            state: 204
        })
    } else {
        const { type, item } = req.body
        if (type === '收藏') {
            db.postsModel.findOne({ _id: item._id }, (err, doc) => {
                if (err) {
                    return res.send({
                        msg: err.message,
                        state: 500
                    })
                } else {
                    db.postsModel.updateOne(
                        { _id: item._id },
                        {
                            "$set": {
                                "collect": doc.collect - 1
                            }
                        },
                        (err, result) => {
                            if (err) {
                                return res.send({
                                    msg: err.message,
                                    state: 500
                                })
                            } else {
                                return res.send({
                                    msg: '更新成功',
                                    state: 200
                                })
                            }
                        })
                }
            })
        } else if (type === '点赞') {
            db.postsModel.findOne({ _id: item._id }, (err, doc) => {
                if (err) {
                    return res.send({
                        msg: err.message,
                        state: 500
                    })
                } else {
                    db.postsModel.updateOne(
                        { _id: item._id },
                        {
                            "$set": {
                                "giveup": doc.giveup - 1
                            }
                        },
                        (err, result) => {
                            if (err) {
                                return res.send({
                                    msg: err.message,
                                    state: 500
                                })
                            } else {
                                return res.send({
                                    msg: '更新成功',
                                    state: 200
                                })
                            }
                        })
                }
            })
        }
    }
}


// 模糊搜索
function search(req, res) {
    const content = req.query.content
    db.postsModel.find({}, (err, docs) => {
        if (err) {
            return res.send({
                msg: err.message,
                state: 500
            })
        } else {
            let list = docs.filter((item) => {
                return item.name.indexOf(content) !== -1 || item.name.indexOf(content[0].toUpperCase()) !== -1
            })
            list = timeSort(list, 'addTime')
            return res.send({
                msg: "搜索数据成功",
                state: 200,
                data: {
                    list
                }
            })

        }
    })
}

// 添加评论
function sendAddCommentRequest(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({
            msg: "无效token",
            state: 204
        })
    } else {
        const { username, content, _id } = req.body
        const addTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
        const comment_id = uuid()
        db.postsModel.updateOne(
            { _id },
            {
                "$addToSet": {
                    "comment": { _id: comment_id, content, addTime, username }
                }
            },
            (err, result) => {
                if (err) {
                    return res.send({
                        msg: err.message,
                        state: 500
                    })
                } else {
                    return res.send({
                        msg: "评论添加成功",
                        state: 200
                    })
                }
            }
        )
    }
}


// 查询评论
function getCommentList(req, res) {
    const _id = req.query._id
    db.postsModel.findOne({ _id }, (err, doc) => {
        if (err) {
            return res.send({
                msg: err.message,
                state: 500
            })
        } else {
            return res.send({
                msg: '获取成功',
                state: 200,
                data: {
                    comment: doc.comment
                }
            })
        }
    })
}

// 删除评论
function delCommentList(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({
            msg: "无效token",
            state: 204
        })
    } else {
        const { _id, comment_id } = req.body
        db.postsModel.updateOne(
            { _id },
            {
                "$pull": {
                    "comment": { _id: comment_id }
                }
            }, (err, result) => {
                if (err) {
                    return res.send({
                        msg: err.message,
                        state: 500
                    })
                } else {
                    console.log(result)
                    return res.send({
                        msg: "删除成功!",
                        state: 200
                    })
                }
            }
        )
    }
}

// 获取用户信息
function getUserInfo(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({
            msg: "无效token",
            state: 204
        })
    } else {
        // 搜索用户信息
        const user_id = token._id
        db.userModel.findOne({ _id: user_id }, (err, doc) => {
            if (err) {
                return res.send({
                    msg: err.message,
                    state: 500
                })
            } else {
                const info = {
                    username: doc.username,
                    age: doc.age,
                    sex: doc.sex,
                    emial: doc.emial
                }
                return res.send({
                    msg: "获取成功",
                    data: {
                        info,
                    }
                })
            }
        })
    }
}

// 添加帖子
function addPosts(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({
            msg: "无效token",
            state: 204
        })
    } else {
        const user_id = token._id
        console.log(user_id)
        const { name, content, title } = req.body
        const _id = uuid()
        const addTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
        // 添加到用户列表中
        db.userModel.updateOne(
            { _id: user_id },
            {
                "$addToSet": {
                    "myPosts": {
                        _id, title,
                        type: "最新",
                        comment: [],
                        arouth: user_id,
                        collect: Number(0),
                        giveup: Number(0),
                        look: Number(0),
                        addTime, content, name,
                    }
                }
            }, (err, result) => {
                if (err) {
                    return res.send({
                        msg: err.message,
                        state: 500
                    })
                } else {
                    return res.send({
                        msg: "添加成功",
                        state: 200
                    })
                }
            }
        )

        // 添加到帖子列表中
        db.postsModel.create({
            _id, title,
            type: "最新",
            comment: [],
            arouth: user_id,
            collect: Number(0),
            giveup: Number(0),
            look: Number(0),
            addTime, content, name
        }, (err, result) => {
            console.log(result)
        })
    }
}

// 获取用户发布的帖子
function Mysend(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({
            msg: "无效token",
            state: 204
        })
    } else {
        const user_id = token._id
        db.userModel.findOne({ _id: user_id }, (err, doc) => {
            if (err) {
                return res.send({
                    msg: err.message,
                    state: 500
                })
            } else {
                return res.send({
                    msg: "获取成功",
                    data: {
                        myPosts: doc.myPosts
                    }
                })
            }
        })
    }
}


// 删除用户发布的帖子(删除两次)
function DelMySend(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({
            msg: "无效token",
            state: 204
        })
    } else {
        const user_id = token._id
        const item = req.body.item
        // 删除用户内的
        db.userModel.updateOne(
            { _id: user_id },
            {
                "$pull": {
                    "myPosts": { _id: item._id }
                }
            },
            (err, result) => {
                if (err) {
                    return res.send({
                        msg: err.message,
                        state: 500
                    })
                } else {
                    return res.send({
                        msg: "删除成功",
                        state: 200
                    })
                }
            }
        )

        // 删除帖子数据集内的
        db.postsModel.remove({ _id: item._id }, (err, result) => {
            if (err) {
                return res.send({
                    msg: err.message,
                    state: 500
                })
            } else {
                console.log('集合内删除', result)
            }
        })
    }
}


// 修改用户信息
function updateUserInfo(req, res) {
    const token = checkToken(req, res)
    if (token === 'tokenKey is error') {
        return res.send({
            msg: "无效token",
            state: 204
        })
    } else {
        const user_id = token._id
        const { username, sex, age, emial } = req.body
        db.userModel.updateOne(
            { _id: user_id },
            {
                "$set": {
                    username,
                    sex,
                    age,
                    emial,
                }
            },
            (err, result) => {
                if (err) {
                    return res.send({
                        msg: err.message,
                        state: 500
                    })
                } else {
                    console.log(result)
                    return res.send({
                        msg: "修改用户信息成功",
                        state: 200
                    })
                }
            }
        )
    }
}

module.exports = {
    register,
    login,
    getHomePageDate,
    getArouthInfo,
    getPostsInfo,
    addCollection,
    addLook,
    getUserCollectOrCommitData,
    removeCollectionOrComment,
    addCollectOrCommentNum,
    removeCollectOrCommentNum,
    search,
    sendAddCommentRequest,
    getCommentList,
    delCommentList,
    getUserInfo,
    addPosts,
    Mysend,
    DelMySend,
    updateUserInfo
}